package cn.le.handler.banks;

import cn.le.bean.enums.EnumMsgCode;
import cn.le.bean.vo.NettyMsg;
import cn.le.bean.ConnectionInfo;
import cn.le.bean.util.ResponseFactory;
import cn.le.bean.vo.NettyServerAddressVO;
import cn.le.inf.HandlerCode;
import cn.le.inf.NettyHandler;
import cn.le.netty.RedisUtils;
import cn.le.util.ConnectionUtil;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 登录处理器
 */
@Component
@HandlerCode(EnumMsgCode.handler_login)
public class LoginHandler implements NettyHandler {

    @Autowired
    private ConnectionInfo connectionInfo;

    @Override
    public void doFilter(ChannelHandlerContext ctx, NettyMsg msg) {
        String uid = String.valueOf(msg.getFid());
        //判断用户是否登录im服务器
        String info = RedisUtils.ImUserUtils.getLogin(uid);
        if (StringUtils.isEmpty(info)) {
            //响应数据
            ctx.channel().writeAndFlush(ResponseFactory.nettyRefuse(msg.getId()));
            ctx.close();//断开链接
            return;
        }
        System.out.println(msg+"  -- 登录服务器");
        //redis记录用户链接信息
        RedisUtils.NettyUtils.setConnect(uid,new NettyServerAddressVO(msg.getFid(),connectionInfo.getIp(),connectionInfo.getPort()));
        //保持用户链接
        ConnectionUtil.active(msg.getFid(),ctx,ctx.channel().id());
        ctx.channel().writeAndFlush(ResponseFactory.nettyOk(msg.getId()));
    }
}
